﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MusicManager : MonoBehaviour
{
    public AudioSource MusicPlayer;
    public GameObject MusicUIPrefab;
    public ScrollRect MusicScrollRect;
    bool isMusicPlaying = true;
    private void Awake()
    {
        Button tempbtn;
        foreach (var item in GlobalData.MusicDictionary.Values)
        {
            tempbtn = Instantiate(MusicUIPrefab).GetComponent<Button>();
            tempbtn.transform.SetParent(MusicScrollRect.content);
            tempbtn.transform.localScale = Vector3.one;
            if (item.CanbeListened)
            {
                tempbtn.onClick.AddListener(delegate () { OnMusicButtonClick(item.Music); });
                tempbtn.GetComponentInChildren<Text>().text = item.Music.name;
            }
            else
                tempbtn.interactable = false;
        }
    }
    IEnumerator StopAndPlayNextMusic(AudioClip music)
    {
        float t = 1f;
        isMusicPlaying = false;
        while (t > 0f)
        {
            t -= Time.deltaTime;
            MusicPlayer.volume = t;
            yield return new WaitForEndOfFrame();
        }
        MusicPlayer.volume = 0f;
        yield return new WaitForSeconds(0.5f);
        MusicPlayer.volume = 1f;
        MusicPlayer.clip = music;
        MusicPlayer.Play();
        isMusicPlaying = true;
    }
    public void OnMusicButtonClick(AudioClip music)
    {
        if (isMusicPlaying)
            StartCoroutine(StopAndPlayNextMusic(music));
    }
}
